package com.github.novicezk.midjourney.support;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.novicezk.midjourney.ProxyProperties;
import com.github.novicezk.midjourney.ProxyProperties.DiscordConfig;
import com.github.novicezk.midjourney.support.handle.DescribeMessageHandler;
import com.github.novicezk.midjourney.support.handle.ImagineMessageHandler;
import com.github.novicezk.midjourney.support.handle.UVMessageHandler;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder;
import org.json.JSONML;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class DiscordStarter implements ApplicationListener<ApplicationStartedEvent> {
	@Resource
	private ProxyProperties properties;

	//@Resource
	//private DiscordMessageListener discordMessageListener;

	@Autowired
	private ImagineMessageHandler imagineMessageHandler;

	@Autowired
	private UVMessageHandler uvMessageHandler;

	@Autowired
	private DescribeMessageHandler describeMessageHandler;

	@Override
	public void onApplicationEvent(ApplicationStartedEvent event) {
		try {
			ObjectMapper mapper = new ObjectMapper();

			String jsonString = mapper.writeValueAsString(properties);
			log.info("discord configuration: {}" , jsonString);

		} catch (JsonProcessingException e) {

		}

		List<DiscordConfig> discordConfigList = properties.getDiscords();
		for (DiscordConfig discordConfig : discordConfigList){
			DefaultShardManagerBuilder builder = DefaultShardManagerBuilder.createDefault(discordConfig.getBotToken(),
					GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT);

			DiscordMessageListener discordMessageListener = new DiscordMessageListener(properties, discordConfig, imagineMessageHandler, uvMessageHandler, describeMessageHandler);

			builder.addEventListeners(discordMessageListener);

			builder.build();
		}


	}

}